﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;


namespace Yunwei
{
    public partial class UdpSendForm : Form
    {

        private UdpClient client = new UdpClient(0);
        private IPEndPoint remoteEndPoint;
        private Thread receiveThread;
        private bool isReceiving = false; // 定义标志位
        public UdpSendForm()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取用户输入的 IP 地址和端口号
                string ipAddress = txtIp.Text;
                int port = int.Parse(txtPort.Text);

                string rtuCode = textRtucode.Text;
                string collectTime = textCollectTime.Text;
                double paraValue = double.Parse(textParaValue.Text);

                string channelNum = textChannelNum.Text;
                string paraType = textParaType.Text;
                string paraNum = textParaNum.Text;


                // 构建要发送的数据
                //string dataToSend = "";
                //MessageBox.Show($"ip:{ipAddress}, port:{port},rtuCode: {rtuCode}, collectTime: {collectTime}, paraValue: {paraValue} channelNum: {channelNum} paraType: {paraType} paraNum: {paraNum}");

                //string dataToSend = $"ip:{ipAddress}, port:{port},rtuCode: {rtuCode}, collectTime: {collectTime}, paraValue: {paraValue}";


                JObject ParentJson = new JObject();
                JObject s1data = new JObject();
                s1data["paramNumber"] = "1";
                s1data["value"] = paraValue;
                           
                JArray jarray = new JArray();
                jarray.Add(s1data);
                
                ParentJson["version"] = "1";
                ParentJson["dataNumber"] = "1";
                ParentJson["rtuCode"] = rtuCode;
                ParentJson["channelNum"] = channelNum;
                ParentJson["collectTime"] = collectTime;
                ParentJson["data"] = jarray;

                //发送数据
                string strdata = JsonConvert.SerializeObject(ParentJson);

                MessageBox.Show($"向UDP发送:{strdata}");

                byte[] sendBytes = Encoding.ASCII.GetBytes(strdata);
                //client.Send(sendBytes, sendBytes.Length, FrmMain.iep);

                // 将数据转换为字节数组
                //byte[] data = Encoding.UTF8.GetBytes(dataToSend);

                // 指定目标 IP 地址和端口
                remoteEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);

                isReceiving = true; // 设置标志位为 true 表示开始接收
                // 启动接收线程
                if (!(receiveThread != null && receiveThread.IsAlive))
                {
                    //MessageBox.Show("接收线程已经在运行中，无需重复启动。");
                    //return;
                    receiveThread = new Thread(ReceiveMessages);
                    receiveThread.IsBackground = true;
                    receiveThread.Start();
                }
                else
                {
                    //MessageBox.Show("接收线程已经在运行中，无需重复启动。");
                }



                // 发送数据
                client.Send(sendBytes, sendBytes.Length, remoteEndPoint);

                //MessageBox.Show("数据发送成功！");
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送数据时出现错误：{ex.Message}");
            }
        }

        private void UdpSendForm_Load(object sender, EventArgs e)
        {



        }

        private void ReceiveMessages()
        {
            try
            {
                while (isReceiving)
                {

                    try
                    {
                        // 接收数据
                        byte[] receiveBytes = client.Receive(ref remoteEndPoint);
                        string returnData = Encoding.UTF8.GetString(receiveBytes);
                        //MessageBox.Show("收到数据！" + returnData);

                        // 在 UI 线程更新界面
                        this.Invoke((MethodInvoker)delegate
                        {
                            textMessage.Text = returnData + Environment.NewLine + textMessage.Text;

                        });

                    }
                    catch (Exception e)
                    {
                        //MessageBox.Show($"通信出错: {e.Message}");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"接收消息出错: {ex.Message}");
            }
        }

        private void UdpSendForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //// 关闭线程和 UdpClient
            //if (receiveThread != null && receiveThread.IsAlive)
            //{
            //    receiveThread.Abort();
            //}
            isReceiving = false; // 设置标志位为 false 表示停止接收



            if (client != null)
            {
                client.Close();
            }

            // 等待线程结束
            if (receiveThread != null && receiveThread.IsAlive)
            {
                //MessageBox.Show("等待线程停止！");
                receiveThread.Join(2000);
                //if (receiveThread.IsAlive)
                //{
                //    // 如果超时仍未结束，可考虑进一步处理
                //    MessageBox.Show("接收线程未能及时结束。");
                //}
                //else
                //{
                //    MessageBox.Show("线程已经停止！");
                //}

            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
